package com.chaosj.skill.guava.caches

import com.google.common.base.Strings
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import com.google.common.cache.RemovalListener
import com.google.common.cache.RemovalNotification

import java.time.Duration
import java.util.concurrent.TimeUnit

/**
 * @Description:
 * @author: caoyangjie
 * @date: 2019年11月2019/11/27日 09:40
 * @Copyright: © 赢时胜
 */
class GuavaCache {
    static void main(args){
        cacheSkills()
    }

    private static void cacheSkills() {
        Cache cache = CacheBuilder.newBuilder()
                .concurrencyLevel(2)
                .initialCapacity(2)
                .maximumSize(4)
                .expireAfterAccess(Duration.ofSeconds(10))
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .removalListener(new RemovalListener<String, String>() {
            @Override
            void onRemoval(RemovalNotification<String, String> notification) {
                println(Strings.lenientFormat("移除key=%s,value=%s,原因为:%s", notification.key, notification.value, notification.cause))
            }
        })
                .build()

        for (int i = 0; i < 6; i++) {
            cache.get(i + "", {
                i
            })
        }
        Thread.sleep(10001L)
        cache.invalidateAll()
        println("缓存数量" + cache.size())
    }
}
